/*
 * @Date         : 2024-03-26 14:34:25
 * @Description  : e福州埋点
 */

import dict from "./dict"
import Base from "../base"
import { useWindowValue } from "../utils"

class Efz extends Base {
  constructor(config = {}) {
    super(config)
    this.sdkConfig = {
      sdk_url: "//systatic.efzhou.com/sensors/sensorsdata.min.js",
      heatmap_url: "//systatic.efzhou.com/sensors/heatmap.min.js",
      platform_url: "//systatic.efzhou.com/sensors/heatmap.min.js",
      name: "sensors",
      use_app_track: true,
      server_url: "//syda.efzhou.com/sa/sa?project=production",
      heatmap: {}
    }
  }

  init() {
    return new Promise(async (resolve, reject) => {
      this.log("e福州埋点开始初始化")
      try {
        await this.#initSdk(this.sdkConfig)
        await uni.$loadScript(this.sdkConfig.platform_url)
        useWindowValue({
          key: "sensors",
          success: (sdk) => {
            this.core = sdk
            this.core.para = this.sdkConfig
            this.isReady = true
            this.emit("ready", this)
            resolve(this)

            this.core.quick("autoTrack", { platForm: "h5" })
            this.core.registerPage({ app_id: "202003190199", app_name: "电影娱乐" })
            this.log("e福州埋点初始化成功")
          },
          fail: () => {
            reject({ errMsg: "未正确获取到埋点加载内容" })
            this.emit("error", { errMsg: "未正确获取到埋点加载内容" })
          }
        })
      } catch (error) {
        reject(error)
        this.emit("error", error)
      }
    })
  }

  #initSdk(config = {}) {
    return new Promise((resolve) => {
      const p = config.sdk_url
      const n = config.name
      const w = window
      const d = document
      const s = "script"
      let x = null
      let y = null
      if (typeof w["sensorsDataAnalytic201505"] !== "undefined") {
        return resolve()
      }

      w["sensorsDataAnalytic201505"] = n
      w[n] =
        w[n] ||
        function (a) {
          return function () {
            ;(w[n]._q = w[n]._q || []).push([a, arguments])
          }
        }
      const ifs = [
        "track",
        "quick",
        "register",
        "registerPage",
        "registerOnce",
        "trackSignup",
        "trackAbtest",
        "setProfile",
        "setOnceProfile",
        "appendProfile",
        "incrementProfile",
        "deleteProfile",
        "unsetProfile",
        "identify",
        "login",
        "logout",
        "trackLink",
        "clearAllRegister",
        "getAppStatus"
      ]
      for (let i = 0; i < ifs.length; i++) {
        w[n][ifs[i]] = w[n].call(null, ifs[i])
      }
      if (!w[n]._t) {
        x = d.createElement(s)
        y = d.getElementsByTagName(s)[0]
        x.async = 1
        x.src = p
        x.setAttribute("charset", "UTF-8")
        y.parentNode.insertBefore(x, y)
        w[n].para = config
      }

      resolve()
    })
  }

  track(name, params = {}) {
    const defaultParams = {
      toon_type: "128",
      app_id: "202003190199",
      app_name: "电影娱乐",
      platform_type: window.TOON_Platform.platform
    }
    if (/toon/.test(navigator.userAgent.toLowerCase())) this.core.identify(window.DISTINNCT_ID)
    this.core.quick("autoTrack")
    const dictName = dict(name)
    const trackName = this.#toHump(name)
    if (dictName === trackName) return
    if (params.name) {
      params.zm_name = params.name
      delete params.name
    }

    const data = Object.assign(defaultParams, params, { element_name: dictName })
    return new Promise((resolve, reject) => {
      this.checkInit({
        success: () => {
          try {
            this.core.track(trackName, data)
            resolve()
          } catch (err) {
            reject(err)
          }
        },
        fail: (err) => reject(err)
      })
    })
  }

  #toHump(name) {
    name = name.replace(/^./, (v) => v.toLocaleUpperCase())
    // eslint-disable-next-line no-useless-escape
    name = name.replace(/\_(\w)/g, function (all, letter) {
      return letter.toUpperCase()
    })
    return "FZZMDY" + name
  }
}

export default Efz
